package com.scu.hotelsystem.controller;

import com.scu.hotelsystem.pojo.Room;
import com.scu.hotelsystem.pojo.RoomCate;
import com.scu.hotelsystem.service.RoomService;
import com.scu.hotelsystem.util.PageInfo;
import com.scu.hotelsystem.util.Result;
import com.scu.hotelsystem.util.search.RoomSearch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class RoomController {

    @Autowired
    private RoomService roomService;

    @RequestMapping("/roomListPage")
    public String roomListPage(){
        return "roomList";
    }

    @RequestMapping("/searchRoomListRest")
    @ResponseBody
    public Result searchRoomCateListRest(RoomSearch roomSearch, PageInfo pageInfo){
        List<Room> roomList;
        RoomCate search;
        int count;
        roomList = roomService.searchRoomList(roomSearch, pageInfo.index(), pageInfo.limit());
        count = roomList.size();

        return new Result(count, roomList);
    }

    @RequestMapping("/roomAddPage")
    public String roomAddPage(){
        return "roomadd";
    }

    @RequestMapping("/addRoom")
    @ResponseBody
    public Result addRoom(Room room){
        int n;
        n = roomService.addRoom(room);

        if (n == 1){
            return new Result();
        }else {
            return new Result(1, "未知错误");
        }
    }

    @RequestMapping("/roomEditPage")
    public ModelAndView roomCateEditPage(int id){

        ModelAndView view;
        view = new ModelAndView("roomedit");

        Room room=roomService.searchRoomById(id);

        if (room!=null){
            view.addObject("room", room);
        }
        return view;
    }

    @RequestMapping("/deleteRoom")
    @ResponseBody
    public Result deleteRoom(int[] idList){
        if (idList.length == 0){
            return new Result(2, "列表为空");
        }

        int n;
        try{
            n = roomService.deleteRoom(idList);
        }catch (IllegalArgumentException e){
            n = 0;
        }

        if (n == 0){
            return new Result(1, "失败");
        }else {
            return new Result();
        }
    }

    @RequestMapping("/updateRoom")
    @ResponseBody
    public Result updateRoom(Room room){
        int n;
        n = roomService.updateRoom(room);

        if (n == 1){
            return new Result();
        }else {
            return new Result(1, "未知错误");
        }
    }

}
